/*
 * @lc app=leetcode.cn id=2461 lang=cpp
 *
 * [2461] 长度为 K 子数组中的最大和
 */
#include <vector>
#include <map>
using namespace std;
// @lc code=start
class Solution {
public:
    long long maximumSubarraySum(vector<int>& nums, int k) {
        long long result =0;
        map<int,int> mp =map<int,int>();
        int l=-1;
        long long sum =0;
        for (int i=0;i<nums.size();++i){
            sum+=nums[i];
            int last_pos=exist_or_set(mp,nums[i],i);
            if (last_pos!=-1){
                for (int j=l+1;j<=last_pos;++j){
                    if (nums[j]!=nums[i]){
                        del(mp,nums[j]);
                    }
                    sum-=nums[j];
                }
                l=last_pos;
            }
             if (i-l>k){
                sum-=nums[l+1];
                del(mp,nums[l+1]);
                l++;
            }
            if (i-l==k&&sum>result){
                result=sum;
            }
           

        }

        return result;
    }
    inline int exist_or_set(map<int,int> & mp,int k,int v){
        auto res =mp.find(k);
        if (res!=mp.end()){
            int tem =res->second;
            res->second=v;
            return tem;
        }else{
            mp[k]=v;
            return -1;
        }
    }
    inline void del(map<int,int> & mp ,int k){
       mp[k]=-1;
    }
};
// @lc code=end

